package com.plate.modules.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.plate.common.core.constants.SecurityConstants;
import com.plate.common.datasource.base.MyBaseServiceImpl;
import com.plate.modules.system.domain.bo.SysMenuQueryBO;
import com.plate.modules.system.domain.po.SysMenu;
import com.plate.modules.system.domain.po.SysRole;
import com.plate.modules.system.domain.vo.Meta;
import com.plate.modules.system.domain.vo.RouterVo;
import com.plate.modules.system.mapper.SysMenuMapper;
import com.plate.modules.system.mapper.SysRoleMapper;
import com.plate.modules.system.service.ISysMenuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName SysMenuServiceImpl
 * @Description TODO
 * @Author jiaxd
 * @Date 2023年10月23日 22:11
 * @Version 1.0
 */

@Slf4j
@Service
public class SysMenuServiceImpl extends MyBaseServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public List<SysMenu> getMuneList(SysMenuQueryBO queryBO, String userId) {
        List<SysMenu> returnList = new ArrayList<>();
        SysRole role = sysRoleMapper.getRoleByUserId(userId);
        List<SysMenu> menuList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(role) && !SecurityConstants.ADMIN.equals(role.getRoleCode())) {
            queryBO.setUserId(Long.parseLong(userId));
            menuList = sysMenuMapper.selectMenuListByUserId(queryBO);
        } else {
            LambdaQueryWrapper<SysMenu> wrapper = new LambdaQueryWrapper<>();
            menuList = sysMenuMapper.selectList(wrapper);
        }

        List<Long> tempList = menuList.stream().map(SysMenu::getId).collect(Collectors.toList());

        for (Iterator<SysMenu> iterator = menuList.iterator(); iterator.hasNext();) {
            SysMenu menu = iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getPid())) {
                recursionFn(menuList, menu);
                returnList.add(menu);
            }
        }
        return returnList;
    }

    @Override
    public List<SysMenu> getMuneTree() {
        List<SysMenu> returnList = new ArrayList<>();
        List<SysMenu> menuList = sysMenuMapper.selectList(null);
        List<Long> tempList = menuList.stream().map(SysMenu::getId).collect(Collectors.toList());

        for (Iterator<SysMenu> iterator = menuList.iterator(); iterator.hasNext();) {
            SysMenu menu = iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getPid())) {
                recursionFn(menuList, menu);
                returnList.add(menu);
            }
        }
        return returnList;
    }



    @Override
    public List<RouterVo> buildMenus(List<SysMenu> muneList) {
        List<RouterVo> routers = new LinkedList<>();
        for (SysMenu menu : muneList) {
            RouterVo router = new RouterVo();
            router.setHidden(menu.getVisible() == 1);
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(new Meta(menu.getMenuName(), menu.getIcon(), true, menu.getPath()));
            List<SysMenu> cMenus = menu.getChildren();
            if ( null != cMenus && cMenus.size() > 0 && "M".equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setHidden(menu.getVisible() == 1);
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(new Meta(menu.getMenuName(), menu.getIcon(), true, menu.getPath()));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else {
                router.setChildren(new ArrayList<>());
            }
            routers.add(router);
        }
        return routers;
    }



    /**
     * 递归列表
     *
     * @param list
     * @param t
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        if (childList == null) {
            System.out.println("gsgsggs");
        }
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<>();
        Iterator<SysMenu> it = list.iterator();
        while (it.hasNext()) {
            SysMenu n = it.next();
            if (n.getPid().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenu menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    public boolean isMenuFrame(SysMenu menu) {
        return menu.getPid().intValue() == 0 && "C".equals(menu.getMenuType())
                && menu.getIsFrame().equals("1");
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
//        if (menu.getPid().intValue() != 0 && isInnerLink(menu)) {
//            routerPath = innerLinkReplaceEach(routerPath);
//        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getPid().intValue() && "M".equals(menu.getMenuType())
                && "1".equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenu menu) {
        String component = "Layout";
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = "ParentView";
        }
        return component;
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenu menu) {
        return menu.getPid().intValue() != 0 && "M".equals(menu.getMenuType());
    }


}
